/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {ToastAndroid, Platform, NativeModules, DeviceEventEmitter, Keyboard,Alert} from 'react-native';
import Toast from 'react-native-root-toast';
import { takeSnapshot, dirs } from "react-native-view-shot";

// var ReactNative = require('react-native');

import md5 from '../lib/md5';

const os = Platform.OS;

var hostName;
if (!__DEV__) {
  global.console = {
    info: () => {},
    log: () => {},
    warn: () => {},
    debug: () => {},
    error: () => {},
  };
}

async function _checkDevice(checkDevice){
  if(Platform.OS == 'ios')
  try {
    var aa = await NativeModules.JsAndroid.checkDevice();
    checkDevice(aa);
  } catch (e) {
      console.log(e);
  }
}

function _fetch(_method, _url, _params, _success, _requestError, _linkError) {
  if(hostName){
    _fetchData(_method, hostName+"portal"+_url, _params, _success, _requestError, _linkError);
  }else{
    NativeModules.JsAndroid.jsGetServerUrl((e) => {
      console.log(e);
    },(e) => {
      hostName = e;
      _fetchData(_method, hostName+"portal"+_url, _params, _success, _requestError, _linkError);
    });
  }
}

function _forward(that, component, name="", did="", parentId="", replace="no", type="Normal" ,sameLevel="",styleState=null){
  const nav = that.props.navigator;
  let route = {
                component: component,
                passProps: {
                  name: name,
                  did: did,
                  parentId: parentId,
                  sameLevel: sameLevel,
                  styleState:styleState,
                },
                type: type,
                
              }
  if(nav) {
    if(replace == "no"){
      nav.push(route);
    }else{
      nav.replace(route);
    }
  }
}

// function _forward(that, component, name="", did="", parentId="", type="Normal" ){
//   const navigateAction = NavigationActions.navigate({

//     routeName: component,

//     params: {},

//     action: NavigationActions.navigate({ routeName: 'SubProfileRoute'})
//   })
// }



// this.props.navigation.dispatch(navigateAction)

function _back(that, params) {
	// if(params){
		/*let type;
	    switch (params.type){
	      case 1 :
	      case 2 :
	      case 3 :
	      case 4 :
	        type = 'cancleCollectionNews';
	        break;
	      case 5 :
	        type = 'cancleCollectionArticle';
	        break;
	      case 8 :
	      case 9 : 
	        type = 'cancleCollectionColumnDetail';
	        break;
	    }
	    if(!params.collectionStatus){
		  DeviceEventEmitter.emit(type,params);
		}*/
    //collectionStatus 收藏状态是否改变，当改变时，重新刷新收藏列表
   
      //alert("cllectionStatus changed");
  // 		DeviceEventEmitter.emit("dealCollection",params.type);
    
	 // }
   Keyboard.dismiss();
  const nav = that.props.navigator;
  const routers = nav.getCurrentRoutes();
  const routeLength = routers.length-1;
  let styleStatus = routers[routeLength].passProps.styleState
  if (routers.length > 1) {
  	
	if((routers[routeLength].passProps.styleState || routers[routeLength].passProps.styleState!="") && routers[routeLength].passProps.sameLevel=="true"){
		DeviceEventEmitter.emit("styleState",{status:styleStatus,id:routers[routeLength].passProps.did});
	}
    nav.pop();
    return true;
  }
  
  if (that.lastBackPressed && (that.lastBackPressed + 2000 >= Date.now())) {  
    //最近2秒内按过back键，可以退出应用。
    NativeModules.JsAndroid.jsOpenAppExit();
  }  
  that.lastBackPressed = Date.now();  
  ToastAndroid.show('再按一次退出应用',ToastAndroid.SHORT);  
  return true;
}

function _updown(data,ic1,ic2,ic3) {
    var updown = {};
    if(data > 0){
      updown.change = data;
      updown.icon = ic1;
    }else if(data < 0){
      updown.change = -data;
      updown.icon = ic2;
    }else{
      updown.change = "";
      updown.icon = ric3;
    }
    return updown;
  }

function _fetchData(_method, _url, _params, _success, _requestError, _linkError){
  // _url = hostName + _url;
  _method = _method || 'get';
  var flag = _params && _params._parts.length?true:false;
  var obj = {method:_method};
  flag?Object.assign(obj, {body:_params}):obj;

  // var now=new Date();
  // var year=now.getFullYear();
  // var month=(now.getMonth()+1).toLocaleString();
  // var monthRs=month.length>1?month:"0"+month;
  // var day=now.getDate().toLocaleString();
  // var dayRs=day.length>1?day:"0"+day;
  // var hours=now.getHours().toLocaleString();
  // var hoursRs=hours.length>1?hours:"0"+hours;
  // var minutes=now.getMinutes().toLocaleString();
  // var minutesRs=minutes.length>1?minutes:"0"+minutes;
  // var dateRs=year+"-"+monthRs+"-"+dayRs+" "+hoursRs+":"+minutesRs;

  var dateRs=new Date().getTime();

  if(_method.toLowerCase()==="get"){
    if(_url.indexOf("?")>0){
      var sUrl=_url.split("?");
      var rs=sUrl[1].split('&');
      rs.push("timesign="+dateRs);
      rs.push("salt=NSDQ11");
      rs.sort().join("");
      var md5rs=md5(rs);
      _url=_url+"&timesign="+dateRs+"&sign="+md5rs.toUpperCase();
    }else{
      var arr = new Array();
      arr.push("timesign="+dateRs);
      arr.push("salt=NSDQ11");
      var rs = arr.sort().join("");
      var md5rs=md5(rs);
      _url=_url+"?timesign="+dateRs+"&sign="+md5rs.toUpperCase();
    }
  }
  if(_method.toLowerCase() === "post"){
    var rsArr=new Array();
    var rs = "";
    if(_params._parts.length){
      _params._parts.map(function(val,i){
        rsArr.push(val.toString().replace(",","="));
      });
    }
    rsArr.push("timesign="+dateRs);
    rsArr.push("salt=NSDQ11");
    var rs=rsArr.sort().join("");
    var md5rs=md5(rs);
    _params.append("timesign",dateRs);
    _params.append("sign",md5rs.toUpperCase());
  }

  fetch(_url,obj).then((response) => response.json())
    .then((responseData) => {
      // console.log(mm);
      console.log(_url);
      console.log(_params);
      console.log(responseData);
      if(responseData.status == 99){
        _success(responseData);
      }else{
        _requestError(responseData);
      }
    }).catch((error) => {
      _linkError();
    });
}

function _paging(params,_url,_success,_requestError,_linkError){
  let formData = new FormData();
  for(var p in params){
    formData.append(p, params[p]);
  }
  _fetch("post", _url, formData, _success, _requestError, _linkError);
}

function _page(_base, responseData){
    var noMoreData = false;
    let np = responseData[_base+"_np"];
    let ap = responseData[_base+"_ap"];
    let total = responseData[_base+"_total"];
    let pageSize = responseData[_base+"_pageSize"];
    let result = responseData[_base];
    if(result.length <= pageSize && np == ap){
      noMoreData = true;
    }
    let resp = {"np":np,"ap":ap,"total":total,"pageSize":pageSize,"noMoreData":noMoreData,"result":result};
    return resp;
}

function _cancelHightlight(data){
	let newData = data.replace(/<red>/g,"");
	let curData = newData.replace(/<\/red>/g,"");
	return curData;
}

function _fetchMore(params, _success, _requestError, _linkError){
  /*
  id  string  节目或话题包ID编号
  type  string  类型：（1：节目、综艺；2:影；3：剧；4资讯-话题包）
  newsType  Integer 新闻分类（1.行业媒体数据，2.全网媒体，3.正面分析数据，4.负面分析数据）
  */
  let formData = new FormData();
  formData.append("id", params.id);
  formData.append("type", params.type);
  formData.append("newsType", params.newsType);
  _fetch("post", "/billboard/moreNews", formData, _success, _requestError, _linkError);
}

function _keyWordHighlight(data){
	/*let newData = data.replace(/<\/red>/g,"<red>");*/
	
	
	/*if(data.match(/(>|<red|<r|<re|red>|<red>)/g)){
		currData= data.replace(/(>|<red|<r|<re|red>|<red>|<)/g,"<red>");
	}else{
		currData= data;
	}
	if(data.match(/<\/red|>|<\/r|<\/re|<\/|<\/red>/g)){
		currData2= currData.replace(/<\/red|>|<\/r|<\/re|<\/|<\/red>/g,"</red>");
	}else{
		currData2= currData;
	}*/
	var arrData = data.split("<red>");
	var newData = [];
	
	for(let i=0;i<arrData.length;i++){
		if(arrData[i].indexOf('</red>')<0){
			newData.push({
				hightLight : false,
				data:arrData[i]
			});
			continue;
		}
		let tmpString = arrData[i].replace(/<\/red>/g,"<red>");
		let tmp=[];
		tmp = tmpString.split('<red>');
		for(let j=0;j<tmp.length;j++){
			let shightLight = true;
			if(j==tmp.length-1){
				shightLight= false;
			}
			newData.push({
				hightLight : shightLight,
				data:tmp[j],
			})
		}
	}
	//搜索关键词高亮
  	/*var mydata = Common.keyWordHighlight('<red>444444</red>333<red>3222</red>7777777<red>444</red>');*/
	
	return newData;
}


/**
  t:时间
  d:天数
**/
function _beforetime(t,d=5){
  var during;
  var time = t.replace(/-/g,"/");
  var old = new Date(time);
  var oldYear = old.getFullYear();
  var oldMonth = old.getMonth()+1 <10 ? "0"+(old.getMonth()+1) : (old.getMonth()+1);
  var oldDay = old.getDate() <10 ? "0"+old.getDate() : old.getDate();
  var now = new Date();
  var minutes = parseInt((now - old)/1000/60); //分钟
 
  if (minutes >= 60){
    var hours = parseInt(minutes/60);
    if(hours >= 24){
      var days = parseInt(hours/24);
      if(days >= 1 && days < d){
        during = days+"天前";
      }else{
        during = oldYear+"-"+oldMonth+"-"+oldDay;
      }
    }else{
      during = hours+"小时前";
    }
  }else{
    during = minutes+"分钟前";
  }
  return during;
}
function _getMainActor(s, c){
  if(s){
    var mainActorArr = s.split('、');
    var arr = [];
    var mainActorArrRs;
    if(mainActorArr.length>c){
      for(var i = 0; i < c; i++){
        arr.push(mainActorArr[i]);
      }
      mainActorArrRs = arr.join('、')+"等";
    }else{
      mainActorArrRs = s;
    }
    return mainActorArrRs;
  }
}
//截图
function _takeToImage(location,name,success,flag=true){
  // cross platform dirs:
  const { CacheDir, DocumentDir, MainBundleDir, MovieDir, MusicDir, PictureDir } = dirs;
  // only available Android:
  const { DCIMDir, DownloadDir, RingtoneDir, SDCardDir } = dirs;
  if( os === 'ios'){
    // UIManager.takeSnapshot(location, {format: 'png', quality: 0.8}).then(
    //     (uri) => console.log(uri)

    // ).catch(
    //     (error) => alert(error)
    // );
    NativeModules.JsAndroid.getImgPath((e)=>{
      takeSnapshot(location,{format: 'jpg', quality: 0.3, path: e, snapshotContentContainer: flag} ).then(
        (uri) => {
          success(uri);
        }
      ).catch(
          (error) => {Toast.show("资源获取失败", { 
            duration: Toast.durations.LONG,
            position: Toast.positions.CENTER,
            shadow: true,
            animation: true,
            hideOnPress: true,
            delay: 0});
          console.log(error);
        }
      );
    });
  }else{
    takeSnapshot(location, {format: 'jpg', quality: 0.3, path: PictureDir+"/"+name+".jpg", snapshotContentContainer: flag }).then(
      (uri) => {
        success(name+".jpg",PictureDir);
      }
    ).catch(
        (error) => {Toast.show("资源获取失败", {
          duration: Toast.durations.LONG,
          position: Toast.positions.CENTER,
          shadow: true,
          animation: true,
          hideOnPress: true,
          delay: 0});
        console.log(error);
      }
    );
  }
  
};
function _isCollection(params, success, error){
  if(typeof loginInfo != 'undefined' && loginInfo){
    let formData = new FormData();
    formData.append("entityId", params.id);
    formData.append("entityType", params.type);
    formData.append("userToken", loginInfo.userToken);
    _fetch("post","/userCenter/collect/check", formData, (responseData) => {
      success();
    },() => {
      error();
      console.log("该篇文章还没有被收藏哦！");
    },() => {
      error();
      console.log("该篇文章还没有被收藏哦！");
    });
  }
}
function _addCollection(params,success){
  if(typeof loginInfo != 'undefined' && loginInfo){
    let formData = new FormData();
    formData.append("entityId", params.id);
    formData.append("entityType", params.type);
    formData.append("userToken", loginInfo.userToken);
    _fetch("post","/userCenter/collect/add", formData, (responseData) => {
      success();
      DeviceEventEmitter.emit('dealCollection',null);
      Toast.show("收藏成功", {
        duration: Toast.durations.LONG,
        position: Toast.positions.CENTER,
        shadow: true,
        animation: true,
        hideOnPress: true,
        delay: 0});
    },() => {
      Toast.show("收藏失败", {
      duration: Toast.durations.LONG,
      position: Toast.positions.CENTER,
      shadow: true,
      animation: true,
      hideOnPress: true,
      delay: 0});
    },() => {
      Toast.show("收藏失败", {
      duration: Toast.durations.LONG,
      position: Toast.positions.CENTER,
      shadow: true,
      animation: true,
      hideOnPress: true,
      delay: 0});
    });
  }else{
    Toast.show("您还尚未登录", {
      duration: Toast.durations.LONG,
      position: Toast.positions.CENTER,
      shadow: true,
      animation: true,
      hideOnPress: true,
      delay: 0});
  }
}
function _deleteCollection(params,success){
  if(typeof loginInfo != 'undefined' && loginInfo){
    let formData = new FormData();
    formData.append("entityId", params.id);
    formData.append("entityType", params.type);
    formData.append("userToken", loginInfo.userToken);
    _fetch("post","/userCenter/collect/delete", formData, (responseData) => {
      success();
      DeviceEventEmitter.emit('dealCollection',null);
      Toast.show("收藏已取消", {
        duration: Toast.durations.LONG,
        position: Toast.positions.CENTER,
        shadow: true,
        animation: true,
        hideOnPress: true,
        delay: 0});
    },() => {
      Toast.show("取消收藏失败", {
      duration: Toast.durations.LONG,
      position: Toast.positions.CENTER,
      shadow: true,
      animation: true,
      hideOnPress: true,
      delay: 0});
    },() => {
      Toast.show("取消收藏失败", {
      duration: Toast.durations.LONG,
      position: Toast.positions.CENTER,
      shadow: true,
      animation: true,
      hideOnPress: true,
      delay: 0});
    });
  }else{
    Toast.show("您还尚未登录", {
      duration: Toast.durations.LONG,
      position: Toast.positions.CENTER,
      shadow: true,
      animation: true,
      hideOnPress: true,
      delay: 0});
  }
}
function _toTransformation(v,p){
  var value = v || 0;
  var p = p || 0;
  var rs = [];
  var temp = 0;
  var unit = '';
  if(value >= 100000000){
    var num =  value / 100000000;
    var round = Math.round(num);
    var toFixed = num.toFixed(p);
    temp = round == toFixed ? round: toFixed;
    unit = '亿';
  }else if(value >= 10000){
    var num = value / 10000;
    var round = Math.round(num);
    var toFixed = num.toFixed(p);
    temp = round == toFixed ? round: toFixed;
    if(temp >= 10000){
      var num = temp / 10000;
      var round = Math.round(num);
      var toFixed = num.toFixed(p);
      temp = round == toFixed ? round: toFixed;
      unit = '亿';
    }else if(temp >= 1000){
      var num = temp / 1000;
      var round = Math.round(num);
      var toFixed = num.toFixed(p);
      temp = round == toFixed ? round: toFixed;
      unit = '千万';
    }else{
      unit = '万';
    }
  }else if(value >= 1000){
    var num = value / 1000;
    var round = Math.round(num);
    var toFixed = num.toFixed(p);
    temp = round == toFixed ? round: toFixed;
    if(temp >= 10){
      var num = temp / 10;
      var round = Math.round(num);
      var toFixed = num.toFixed(p);
      temp = round == toFixed ? round: toFixed;
      unit = '万';
    }else{
      unit = '千';
    }
  }else{
    var num = value / 100;
    var round = Math.round(num);
    var toFixed = num.toFixed(p);
    temp = round == toFixed ? round: toFixed;
    if(temp >= 10){
      var num = temp / 10;
      var round = Math.round(num);
      var toFixed = num.toFixed(p);
      temp = round == toFixed ? round: toFixed;
      unit = '千';
    }else{
      temp = value;
      unit = '';
    }
  }
  rs.value = String(temp);
  rs.unit = unit;
  return rs;
}
/***
  将阿拉伯数字转换成大写数字，如：234 对应 二百三十四，
  本函数只适用于0～999范围内的数字转换
***/
function _toUpper(period){
  let rsArr = [];
  period = period.toString();
  let arr = period.split("");
  let length = period.length;
  for(var i = 0; i < length; i++){
    let rs = "";
    switch (arr[i]){
      case "0":
        if(arr[length - 2] == arr[length - 1]){
          break;
        }
        if(length == 2 && i == 1){
          break;
        }
        if(length == 3 && i == 2){
          break;
        }
        rs = "零";
        break;
      case "1":
        if(length == 2 && i == 0){
          break;
        }
        rs = "一";
        break;
      case "2":
        rs = "二";
        break;
      case "3":
        rs = "三";
        break;
      case "4":
        rs = "四";
        break;
      case "5":
        rs = "五";
        break;
      case "6":
        rs = "六";
        break;
      case "7":
        rs = "七";
        break;
      case "8":
        rs = "八";
        break;
      case "9":
        rs = "九";
        break;
      default :
        rs = "";
        break;
    }
    rsArr.push(rs);      
  }
  if(length == 2 && arr[0] == "1"){
    rsArr.splice(0,0,"十");
  }else if(length == 2){

    rsArr.splice(1,0,"十");
  }
  if(length == 3){
    rsArr.splice(1,0,"百");
    if(length == 3 && arr[1] == "0"){}else{
      rsArr.splice(3,0,"十");
    }
  }
  return rsArr.join("");  
}
function forwardSetting(){
    NativeModules.JsAndroid.getAppDetailSettingIntent();
}

function _userTip(tip){
  Alert.alert(
    '提示',
    tip,
    [
      {text: '取消',style: 'cancel'},
      {text: '去设置', onPress: () => forwardSetting()},
    ]
  )
}
var _Environments = {
    production:{
      "fetchData": _fetch,
      "onBack": _back,
      "onForward": _forward,
      "updown": _updown,
      "beforeTime": _beforetime,
      "takeToImage": _takeToImage,
      "isCollection": _isCollection,
      "addCollection": _addCollection,
      "deleteCollection": _deleteCollection,
      "getMainActor": _getMainActor,
      "toTransformation": _toTransformation,
      "keyWordHighlight": _keyWordHighlight,
      "cancelHightlight":_cancelHightlight,
      "fetchMore": _fetchMore,
      "toUpper":_toUpper,
      "userTip":_userTip,
      "paging":_paging,
      "page": _page,
      "checkDevice": _checkDevice
    },
    staging:{
      "fetchData": _fetch,
      "onBack": _back,
      "onForward": _forward,
      "updown": _updown,
      "beforeTime": _beforetime,
      "takeToImage": _takeToImage,
      "isCollection": _isCollection,
      "addCollection": _addCollection,
      "deleteCollection": _deleteCollection,
      "getMainActor": _getMainActor,
      "toTransformation": _toTransformation,
      "keyWordHighlight": _keyWordHighlight,
      "cancelHightlight":_cancelHightlight,
      "fetchMore": _fetchMore,
      "toUpper":_toUpper,
      "userTip":_userTip,
      "paging":_paging,
      "page": _page,
      "checkDevice": _checkDevice
    },
    development:{
      "fetchData": _fetch,
      "onBack": _back,
      "onForward": _forward,
      "updown": _updown,
      "beforeTime": _beforetime,
      "takeToImage": _takeToImage,
      "isCollection": _isCollection,
      "addCollection": _addCollection,
      "deleteCollection": _deleteCollection,
      "getMainActor": _getMainActor,
      "toTransformation": _toTransformation,
      "keyWordHighlight": _keyWordHighlight,
      "cancelHightlight":_cancelHightlight,
      "fetchMore": _fetchMore,
      "toUpper":_toUpper,
      "userTip":_userTip,
      "paging":_paging,
      "page": _page,
      "checkDevice": _checkDevice
  }
}
function getEnvironments(){
  return _Environments[process.env.NODE_ENV];
}
var Environments = getEnvironments();
module.exports = Environments;

